<template>
  <el-dialog
    :model-value="KpiDialogVisible"
    :title="title"
    align-center
    draggable
  >
    <el-form :model="form" label-width="120px">
      <el-form-item label="员工姓名">
        <el-select
          v-model="form.empId"
          placeholder="请选择员工"
          filterable
          remote
        >
          <el-option
            v-for="item in UserList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
            {{ item.name }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-for="(item, index) in form.positionList"
        :key="index"
        :label="'岗位' + (index + 1)"
        :prop="'positionList.' + index + '.value'"
      >
        <div>
          <!--<el-select
            v-model="item.positionId"
            placeholder="请选择岗位"
          >
            <el-option
              v-for="item in PositionList"
              :key="item.id"
              :label="item.position"
              :value="item.id"
            >
              {{ item.position }}
            </el-option>
          </el-select>-->
          <el-card style="height: 300px; overflow-y: scroll" shadow="never">
            <el-tree
              ref="selectTree"
              :data="PositionList"
              show-checkbox
              node-key="id"
              check-strictly="true"
              highlight-current
              v-model="test"
              :default-expanded-keys="expanded[index] ? [expanded[index]] : []"
              :default-checked-keys="checked[index] ? [checked[index]] : []"
              @check-change="
                (node, checked, data) => handleClick(node, checked, data, index)
              "
              :props="defaultProps"
            >
            </el-tree>
          </el-card>
        </div>
        <div>
          <el-input
            v-model="item.posiPercent"
            style="width: 150px; margin-left: 10px"
          />%
        </div>
        <div>
          <el-button
            @click.prevent="removeDomain(item)"
            type="primary"
            icon="Minus"
            circle
            style="margin-left: 20px"
          />
        </div>
      </el-form-item>
      <el-form-item label="">
        <el-button
          @click="addDomain(index + 2)"
          type="primary"
          icon="Plus"
          size="large"
          circle
        />
      </el-form-item>
      <el-form-item>
        <el-button style="width: 200px" @click="onClose">取消</el-button>
        <el-button style="width: 200px" type="primary" @click="submitForm"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  onBeforeMount,
  reactive,
  defineProps,
  defineEmits,
  watch,
} from "vue";
import {
  getPositionList,
  addEmpPosition,
  getEmpPositionList,
  updateEmpPosition,
  getCheckTree,
} from "@/api/position";
import { getEmpList } from "@/api/employee";
import { ElMessage } from "element-plus";
const form = reactive({
  empName: "",
  empId: "",
  positionList: [],
});
const defaultProps = {
  children: "children",
  label: "label",
  id: "id",
};
const expanded = ref([]);
const checked = ref([]);

const KpiDialogVisible = ref(true);
const props = defineProps({
  KpiDialogVisible: {
    type: Boolean,
    required: true,
  },
  close: {
    type: Function,
    default: () => {},
  },
  update: {
    type: Function,
    default: () => {},
  },
  editForm: {
    type: Object,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  },
});

const PositionList = ref([]);
const UserList = ref([]);
onBeforeMount(() => {
  getCheckTree().then((data) => {
    PositionList.value = data.data;
  });
  getEmpList().then((data) => {
    for (let i of data.data) {
      i.id = String(i.id);
      UserList.value.push(i);
    }
  });
});

watch(props, (newValue, oldValue) => {
  form.empName = newValue.editForm.empName;
  form.empId = newValue.editForm.empId;
  expanded.value = [];
  checked.value = [];
  if (newValue.type == "edit") {
    let empId = newValue.editForm.empId;
    getEmpPositionList({ empId }).then((data) => {
      form.positionList = data.data;
      for (let i of data.data) {
        expanded.value.push(String(i.deptId));
        checked.value.push(String(i.positionId));
      }
    });
    getCheckTree().then((data) => {
      PositionList.value = data.data;
    });
  }
  if (newValue.type == "add") {
    expanded.value.splice(0, expanded.length);
    checked.value.splice(0, checked.length);
    form.positionList = [
      {
        positionId: "",
        posiPercent: "",
      },
    ];
  }
});

const test = ref([]);
const selectTree = ref(null);
const handleClick = (node, checked, data, index) => {
  //if (selectTree.value[index].getCheckedKeys().length != 0) {
  if (selectTree.value[index].getCheckedKeys().length >= 2) {
    if (checked) {
      if (
        node.$treeNodeId >
        selectTree.value[index].getCheckedNodes()[0].$treeNodeId
      ) {
        selectTree.value[index].setChecked(
          selectTree.value[index].getCheckedNodes()[0],
          false
        );
      } else {
        selectTree.value[index].setChecked(
          selectTree.value[index].getCheckedNodes()[1],
          false
        );
      }
      form.positionList[index].positionId =
        selectTree.value[index].getCheckedNodes()[0].id;
      form.positionList[index].position =
        selectTree.value[index].getCheckedNodes()[0].label;
    }
  } else if (selectTree.value[index].getCheckedKeys().length == 1) {
    form.positionList[index].positionId =
      selectTree.value[index].getCheckedNodes()[0].id;
    form.positionList[index].position =
      selectTree.value[index].getCheckedNodes()[0].label;
  }
  //}
  else {
    if (checked) {
      form.positionList[index].positionId =
        selectTree.value[index].getCheckedNodes()[0].id;
      form.positionList[index].position =
        selectTree.value[index].getCheckedNodes()[0].label;
    } else {
      form.positionList[index].positionId = "";
      form.positionList[index].position = "";
    }
  }
};

const onClose = () => {
  props.close();
};

const removeDomain = (item) => {
  const index = form.positionList.indexOf(item);
  if (index !== -1) {
    form.positionList.splice(index, 1);
  }
};

const addDomain = (index) => {
  form.positionList.push({
    kpiKey: index,
    empId: form.positionList[0].empId,
    positionId: "",
    posiPercent: "",
  });
};

const submitForm = () => {
  if (props.type == "add") {
    addEmpPosition(form).then((data) => {
      if (data.code == 200) {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        props.close();
        props.update();
      } else {
        ElMessage.error("新增失败");
      }
    });
  } else if (props.type == "edit") {
    updateEmpPosition(form).then((data) => {
      if (data.code == 200) {
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        props.close();
        props.update();
      } else {
        ElMessage.error("编辑失败");
      }
    });
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label:before {
  content: "* ";
  color: red;
}
.ins {
  ::v-deep .el-form-item__label:before {
    content: " ";
  }
}
</style>
